﻿namespace Sai.Core.Sandcastle
{
	using System;
	using System.IO;

	public static class StringExtensions
	{
		public static string ExtractQuotedText(this string text)
		{
			string quote = text;

			int openingQuote = text.IndexOf('\"') + 1;

			if (openingQuote > 0)
			{
				int closingQuote = text.IndexOf('\"', openingQuote + 1);
				if (closingQuote > 0)
				{
					quote = text.Substring(openingQuote, closingQuote - openingQuote);
				}
			}

			return quote;
		}

		public static string ContainingFolder(this string path)
		{
			string folderName = Path.GetDirectoryName(path);

			if (folderName == ".")
			{
				folderName = Environment.CurrentDirectory;
			}

			return folderName;
		}

		public static string RelativeToFolder(this string fullPath, string basePath)
		{
			Uri uri1 = new Uri(fullPath, UriKind.RelativeOrAbsolute);

			if (uri1.IsAbsoluteUri)
			{
				Uri uri2 = new Uri(basePath + "/", UriKind.Absolute);
				Uri relativeUri = uri2.MakeRelativeUri(uri1);

				return Uri.UnescapeDataString(relativeUri.ToString()).Replace('/', Path.DirectorySeparatorChar);
			}

			return fullPath;
		}

		public static string AbsoluteFromFolder(this string relativePath, string basePath)
		{
			Uri relativeUri = new Uri(relativePath, UriKind.RelativeOrAbsolute);

			if (relativeUri.IsAbsoluteUri)
			{
				return relativePath;
			}

			Uri baseUri = new Uri(basePath + "/", UriKind.Absolute);
			return new Uri(baseUri, relativeUri).LocalPath;
		}
	}
}
